//
//  DSUnitExerciseViewModel.m
//  DSJY
//
//  Created by 冯华强 on 16/10/19.
//  Copyright © 2016年 dsjy. All rights reserved.
//  单元练习VM

#import "DSUnitExerciseViewModel.h"
#import "DSUnitSubContent.h"
#import "DSAccountViewModel.h"
#import "DSUnit.h"
#import "DSUnitExercise.h"
#import "DSUnitListening.h"
#import "DSUnitListeningContent.h"
#import "DSMyLearnInfo.h"
#import "NSString+Extension.h"
#import "MBProgressHUD+MJ.h"

@interface DSUnitExerciseViewModel ()
//模型
@property (nonatomic, strong, readwrite) DSUnitSubContent *unitSubContent;
//单元中的所有音频
@property (nonatomic, strong, readwrite) NSMutableArray<DSUnitListeningContent *> *audioList;
//音频下载请求命令
@property (nonatomic, strong, readwrite) RACCommand *audioDownloadCommand;
//requestCommand请求成功，获取信号，分解DSUnitListening
@property (nonatomic, strong, readwrite) RACSubject *requestSuccessSignal;
//表示全部加锁，比如过期，禁用，否则反之
@property(nonatomic, assign) BOOL userExist;
@end

@implementation DSUnitExerciseViewModel

#pragma mark - 懒加载
- (RACSubject *)requestSuccessSignal
{
    if (_requestSuccessSignal == nil) {
        _requestSuccessSignal = [RACSubject subject];
    }
    return _requestSuccessSignal;
}

- (NSMutableArray<DSUnitListeningContent *> *)audioList
{
    if (_audioList == nil) {
        _audioList = [NSMutableArray<DSUnitListeningContent *> array];
    }
    return _audioList;
}

#pragma mark - 初始化
- (instancetype)initWithUnitId:(NSString *)unitId userExist:(BOOL)userExist
{
    if (self = [super init]) {
        //保存urlString
        self.unitId = unitId;
        self.userExist = userExist;
        //延迟时间
        self.timeDelay = 1.5;
        //绑定事件
        [self initialBind];
    }
    return self;
}

- (void)initialBind
{
    @weakify(self);
    //初始化数据
    self.requestCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self);
                
        RACSignal *learnCourseSignal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            [DSNetworkTool learnCourseWithParams:[DSAccountViewModel sharedAccount].account unitid:self.unitId userExist:self.userExist success:^(NSDictionary *responseObject) {
                //返回值
                self.response = [YQResponse mj_objectWithKeyValues:responseObject];
                [self veriResponse:self.response finishedCallBack:^{
                    //列表
                    self.unitExercise = [DSUnitExercise mj_objectWithKeyValues:responseObject[@"attrs"]];
                }];
                [subscriber sendCompleted];
            } failure:^(NSError *error) {
                MTLog(@"%@", error);
                [SVProgressHUD showErrorWithStatus:@"系统异常!"];
//                [subscriber sendNext:error];
                [subscriber sendCompleted];
            }];
            return nil;
        }];
        
        RACSignal *downSignal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            [DSNetworkTool downFileWithUrlString:self.unitExercise.jsonpathString unitId:self.unitId success:^(NSString *urlString) {
                
                NSData *JSONData = [NSData dataWithContentsOfFile:urlString];
                NSError *error = nil;
                id jsonObject = [NSJSONSerialization JSONObjectWithData:JSONData
                                                                options:NSJSONReadingAllowFragments
                                                                  error:&error];
                if (error == nil) {
                    self.unitSubContent = [DSUnitSubContent mj_objectWithKeyValues:jsonObject];
                }
                
                [subscriber sendNext:self.unitSubContent];
                [subscriber sendCompleted];
            } failure:^(NSError *error) {
                if ([NSString isEmptyWithStr:self.unitExercise.unitid]) {
                    [MBProgressHUD showText:@"您还没有学习记录，快去学习吧!"];
                }else{
                    [SVProgressHUD showErrorWithStatus:@"系统异常!"];
                }
                [subscriber sendCompleted];
            }];
            return nil;
        }];
        
        return [learnCourseSignal concat:downSignal];
    }];
    
    //如果验证通过，调用命令信号
    [self.requestCommand.executionSignals.switchToLatest subscribeNext:^(id x) {
        @strongify(self);
        //既能拿到A信号的值，又能拿到B的值
        if ([x isKindOfClass:[DSUnitSubContent class]]){
            
            if (!self.unitSubContent) return;
            
            //清除所有的音频集合
            [self.audioList removeAllObjects];
            
            //重新添加
            NSArray<DSUnitListening *> *listeningList = self.unitSubContent.listening;
            if (!listeningList || listeningList.count == 0) return;
            
            DSUnitListening *listening = listeningList[0];
            if (listening.audio.count == 0) return;
            
            //保存所有音频
            for (NSInteger i = 0; i < listeningList.count; i++) {
                DSUnitListening *listening = listeningList[i];
                //判断当前是故事会还是正常的
                NSArray<DSUnitListeningContent *> *audioList = (self.unitExercise.exerciseType == DSUnitExerciseTypeNormal) ? listening.randomAudioList : listening.audio;
                [self.audioList addObjectsFromArray:audioList];
            }
            
            //下载第一个audio音频
            [self.audioDownloadCommand execute:self.audioList[0]];
            
            if (self.audioList.count > 1) {
                //下载第二个audio音频
                [[self createDownFileCommand] execute:self.audioList[1]];
            }
            
            //发送请求成功的信号
            [self.requestSuccessSignal sendNext:nil];
        }
    }];
    
    //设置请求时的提示框
    [self executingWithCommand:self.requestCommand];
    
    //音频下载
    self.audioDownloadCommand = [self createDownFileCommand];
    
    //成绩成绩提交cmd
    [self createInsertMyLearninginfoCommand];
}

- (RACCommand *)createDownFileCommand
{
    return [[RACCommand alloc] initWithSignalBlock:^RACSignal *(DSUnitListeningContent *listeningContent) {
        
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            [DSNetworkTool downFileWithUrlString:listeningContent.srcString unitId:self.unitId index:listeningContent.name success:^(NSString *urlString) {
//            [DSNetworkTool ossDownFileWithPath:listeningContent.src unitId:self.unitId success:^(NSString *urlString) {
            
                listeningContent.filePath = urlString;
                NSInteger i = [self.audioList indexOfObject:listeningContent] + 1;
                [subscriber sendNext:@(i)];
                [subscriber sendCompleted];
            } failure:^(NSError *error) {
                MTLog(@"list:%@======src:%@", listeningContent, listeningContent.srcString);
                MTLog(@"下载音频失败，将重新下载!");
//                [SVProgressHUD showErrorWithStatus:@"下载音频失败，将重新下载!"];
                [subscriber sendNext:error];
                [subscriber sendCompleted];
            }];
            return nil;
        }];
    }];
}

- (void)createInsertMyLearninginfoCommand
{
    _insertMyLearninginfoCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(DSMyLearnInfo *myLearnInfo) {
        
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            if (myLearnInfo == nil) {  //不上传成绩
                [subscriber sendNext:nil];
                [subscriber sendCompleted];
            }else{
                [DSNetworkTool insertMyLearninginfoWithParams:myLearnInfo success:^(NSDictionary *responseObject) {
                    //返回值
                    self.response = [YQResponse mj_objectWithKeyValues:responseObject];
                    [self veriResponse:self.response finishedCallBack:^{
                        [subscriber sendNext:responseObject[@"autoUnlockUnit"]];
                        [subscriber sendCompleted];
                    }];
                } failure:^(NSError *error) {
                    [SVProgressHUD showErrorWithStatus:@"成绩上传失败!"];
                    //[subscriber sendNext:nil];
                    [subscriber sendCompleted];
                }];
            }
            return nil;
        }];
    }];
}

@end
